package com.hqyj.javaSpringBoot.modules.common.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 抽象实体bean，将 id 和 createDate 抽取出去
 * 只要JPA命名且用到自动生成表的bean都要继承于AbstractEntity（父类）
 *
 * @MappedSuperclass 表示所有bean类的超类
 */
@MappedSuperclass
public class AbstractEntity implements Serializable {
    /**
     * 唯一标识注解
     * @GeneratedValue 策略：IDENTITY | TABLE | SEQUENCE | AUTO
     *      使用IDENTITY自增长策略
     * @Column 设置列的属性
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false, updatable = false)
    private Integer id;

    /**
     * @JsonSerialize 如使用了新的时间类，就需要LocalDateTimeSerializer进行序列化
     * 序列化不成功会报错
     */
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(updatable = false)
    private LocalDateTime createDate;

    /**
     * @PrePersist 表在持久化之前实现
     * 在 insert 之前，该方法被调用
     */
    @PrePersist
    public void preInsert(){
        setCreateDate(LocalDateTime.now());
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public LocalDateTime getCreateDate() {
        return createDate;
    }

    public void setCreateDate(LocalDateTime createDate) {
        this.createDate = createDate;
    }
}
